import storage from "store";
import store from "@/store";
import { whiteList } from "./basics.router";
import { Router, RouteRecordRaw } from "vue-router";

const loginPath = "/login";
const defultPath = "/";

// 权限验证

export const permission = (router: Router) => {
  router.beforeEach((to, from, next) => {
    if (storage.get("token")) {
      if (to.path === loginPath) {
        next({ path: defultPath });
      } else {
        if (!store.state.user.name) {
          console.log("这错了4");
          store
            .dispatch("user/userInfo")
            .then(() => {
              console.log("这错了5");
              store.dispatch("user/menu").then((e) => {
                console.log('这错了6');
                e.forEach((item: RouteRecordRaw) => {
                  router.addRoute(item);
                });
                router.addRoute({ path: "/:pathMatch(.*)*", redirect: "/404" });
                const redirect = from.query.redirect as string | undefined;
                if (redirect && to.fullPath === redirect) {
                  console.log('这错了7');
                  next({ ...to, replace: true });
                } else {
                  console.log('这错了8');
                  next({ ...to });
                }
              });
            })
            .catch(() => {
              console.log('这错了9');
              storage.remove("token");

              next({ path: loginPath, query: { redirect: to.fullPath } });
            });
        } else {
          next();
        }
      }
    } else {
      if (whiteList.includes(to.path)) {
        next();
      } else {
        next({ path: loginPath, query: { redirect: to.fullPath } });
      }
    }
  });
};
